package top.fyxxxx.downloader.Activities;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.fyxxxx.downloader.R;
import top.fyxxxx.downloader.Service.MyService;
import top.fyxxxx.downloader.utils.DownloadListener;
import top.fyxxxx.downloader.utils.DownloadManager;
import top.fyxxxx.downloader.utils.DownloadTask;
import top.fyxxxx.downloader.utils.History;
import top.fyxxxx.downloader.utils.HistoryAdapter;
import top.fyxxxx.downloader.utils.LocalSession;
import top.fyxxxx.downloader.utils.SqlUtil;
import top.fyxxxx.downloader.utils.TaskListener;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private Context context;
    private EditText editText;
    private LinearLayout show_layout,download_layout;
    private SqlUtil sqlUtil=SqlUtil.getInstance(this);
    List<History> list;
    ListView listView;
    Map<String,DownloadTask> map=new HashMap<String, DownloadTask>();
    private static String Permission[]={Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_main);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        setTitle(R.string.app_name);
        show_layout=findViewById(R.id.show_layout);
        download_layout=findViewById(R.id.download_layout);
        button=(Button)findViewById(R.id.download);
        editText=(EditText)findViewById(R.id.link);
        listView=(ListView)findViewById(R.id.show_listview);
        list=sqlUtil.getAllHistory();
        listView.setAdapter(new HistoryAdapter(MainActivity.this,map,list,listView));
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, final long id) {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("确认删除吗");
                builder.setTitle("提示");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.setPositiveButton("确定",new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int which) {
                        list=sqlUtil.getAllHistory();
                        History temp=list.get(position);
                        DownloadTask task=(DownloadTask) map.get(temp.getFileName());
                        if(task==null) {
                            System.out.println("nulllllllll");
                        }
                        else{
                            task.pause();
                        }
                        sqlUtil.deleteHistory(temp);
                        File f=new File(temp.getFilePath());
                        f.delete();
                        f=new File(temp.getFilePath()+".download");
                        f.delete();
                        list=sqlUtil.getAllHistory();
                        listView.setAdapter(new HistoryAdapter(MainActivity.this,map,list,listView));
                    }
                });
                builder.create().show();
                return false;
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText()==null||editText.getText().toString().equals("")){
                    Toast.makeText(context,"请输入下载地址",Toast.LENGTH_SHORT).show();
                    return ;
                }
                final String url=editText.getText().toString();
                //String url="http://129.211.81.177/download/test2.jpg";
                String[]strs=url.split("/");
                final String filename=strs[strs.length-1];
                final DownloadTask task = DownloadManager.getInstance(MainActivity.this).getTask(url,
                        SqlUtil.getInstance(MainActivity.this).getDownloadPath()+"/"+filename);
                Intent intent=new Intent(MainActivity.this,MyService.class);
                intent.putExtra("task",task.toString());
                LocalSession.temp(task.toString(),task);
                list=sqlUtil.getAllHistory();
                listView.setAdapter(new HistoryAdapter(context,map,list,listView));
                for(int i=0;i<list.size();i++){
                    if(list.get(i).getFileName().equals(filename)){
                        Toast.makeText(MainActivity.this,"该URL已经下载过了",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                TaskListener listener=new TaskListener(context,filename,sqlUtil.getDownloadPath()+"/"+filename,url,listView,map,task);
                task.addListener(listener);
                startService(intent);
                showListView();
            }
        });
        requestPermission();
    }
    private void requestPermission(){
        ActivityCompat.requestPermissions(this,Permission,1);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case R.id.action_downloadtask:
                showListView();
                break;
            case R.id.action_about:
                startActivity(new Intent(MainActivity.this, AboutActivity.class));
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed(){
        if(show_layout.getVisibility()==View.VISIBLE){
            show_layout.setVisibility(View.GONE);
            download_layout.setVisibility(View.VISIBLE);
        }
        else{
            super.onBackPressed();
        }
    }
    public void showListView(){
        show_layout.setVisibility(View.VISIBLE);
        download_layout.setVisibility(View.GONE);
    }
}
